package at.ac.tuwien.swa.sparrow.server.component

import at.ac.tuwien.swa.sparrow._
import at.ac.tuwien.swa.sparrow.common.{AccountDoesNotExistException, Ticket}
import at.ac.tuwien.swa.sparrow.server.persistence.AccountRepository
import com.typesafe.scalalogging.log4j.Logging
import javax.inject.Inject
import org.springframework.stereotype.Component

@Component
class BillingEngine @Inject()(accountRepository: AccountRepository) extends Logging {

	def buy(id: Long, amount: Int) = accountRepository findOne id match {
		case None => throw AccountDoesNotExistException(id)
		case Some(a) if amount <= 0 => throw new IllegalArgumentException(a.toString)
		case Some(a) => val old = a.credits.getAndAdd(amount)
			logger.info(s"Client ${a.username} bought $amount credits ($old -> ${a.credits})")
			a.credits.get()
	}

	def pay(id: Long, ticket: Ticket) = accountRepository findOne id match {
		case None => throw AccountDoesNotExistException(id)
		case Some(a) => logger.info(s"User $id has to pay for $ticket")
			a.credits.addAndGet(-SEARCH_COSTS)
			ticket
	}
}
